<script setup lang="ts">
import { useTagsViewStore } from "@/pinia/stores/tags-view"
import type { PageTableRequestData, TableItem, ViewInfo } from "@/common/apis/train/type"
import { searchTaskApi } from "@/common/apis/train"
import { usePagination } from "@/common/composables/usePagination"
import { getProjectId } from "@/common/utils/cache/local-storage"
import { Search } from "@element-plus/icons-vue"
import { debounce, isEmpty } from "lodash-es"
import ScenarioCard from "./ScenarioCard.vue"
import { createImportTask, getTaskInfoApi } from "@/common/apis/train"
import { INIT_DATE_COLLECTION } from "@/common/apis/train/type"
const tagsViewStore = useTagsViewStore()
import { cloneDeep } from "lodash-es"
import { closeRoute } from "@@/composables/useCloseRouteListener"
import { useRouter,useRoute } from "vue-router"

const router = useRouter()
const route = useRoute()
const selectedId = ref()
const { paginationData } = usePagination()

const searchKey = ref<string>()
const loading = ref<boolean>(false)
const tableData = ref<TableItem[]>([])
const cardScrollContainer = ref()

// 无限滚动状态
const isLoading = ref(false)
const hasMoreData = ref(true)

paginationData.pageSize = 2

// 构建请求参数
function buildRequestParams() {
  const params: PageTableRequestData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    task_mode: "Train",
    task_name: searchKey.value,
    ...(getProjectId() ? { project_id: getProjectId() } : {})
  }
  return params
}

// 搜索处理
function handleSearch() {
  if (paginationData.currentPage === 1) {
    getTableData()
  } else {
    paginationData.currentPage = 1
  }
}

// 获取表格数据（首次加载或搜索）
function getTableData() {
  // 重置状态
  hasMoreData.value = true
  paginationData.currentPage = 1
  const params = buildRequestParams()
  loading.value = true
  return searchTaskApi(params)
    .then(({ data }) => {
      // 检查是否还有更多数据
      hasMoreData.value = data.rows.length >= paginationData.pageSize
      // 更新表格数据
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
      hasMoreData.value = false
    })
    .finally(() => {
      loading.value = false
      // 检查是否需要立即加载更多
      checkAndLoadMore()
    })
}

// 检查并加载更多数据（如果内容不足以滚动）
function checkAndLoadMore() {
  nextTick(() => {
    cardScrollContainer.value = document.querySelector(".mode-wrapper")
    if (cardScrollContainer.value
      && cardScrollContainer.value.scrollHeight - cardScrollContainer.value.scrollTop - cardScrollContainer.value.clientHeight <= 100
      && hasMoreData.value) {
      cardLoadData()
    }
  })
}

function cardLoadData() {
  if (isLoading.value || !hasMoreData.value) {
    return Promise.resolve()
  }

  isLoading.value = true
  paginationData.currentPage++

  const params = buildRequestParams()
  return searchTaskApi(params)
    .then(({ data }) => {
      hasMoreData.value = data.rows.length >= paginationData.pageSize
      tableData.value = [...tableData.value, ...data.rows]
      paginationData.total = data.total
    })
    .catch((error) => {
      console.error("加载失败:", error)
      hasMoreData.value = false
    })
    .finally(() => {
      isLoading.value = false
      checkAndLoadMore()
    })
}

// 切换选择
function handleToggleSelect(row: TableItem | { task_id: string }) {
  // 如果点击的是当前已选中的卡片，则取消选择
  if (selectedId.value === row.task_id) {
      selectedId.value = 'no-select'
  } else {
    // 否则选中当前卡片
    selectedId.value = row.task_id
  }
}

// 添加卡片滚动处理函数
const handleCardScroll = debounce(() => {
  if (!cardScrollContainer.value) return

  const {
    scrollTop,
    scrollHeight,
    clientHeight
  } = cardScrollContainer.value

  // 当距离底部 100px 时触发加载
  if (scrollHeight - scrollTop - clientHeight <= 100) {
    cardLoadData()
  }
}, 200)

// 无限滚动配置
const infiniteScrollConfig = {
  // 距离底部多少像素时触发加载
  distance: 100,
  // 是否禁用
  disabled: computed(() => isLoading.value || !hasMoreData.value),
  // 立即检查
  immediate: true
}

// 修改 onMounted 钩子，确保正确获取卡片容器
onMounted(() => {
  handleSearch()
  // 为表格添加滚动监听
  nextTick(() => {
    cardScrollContainer.value = document.querySelector(".mode-wrapper")
    if (cardScrollContainer.value) {
      cardScrollContainer.value.addEventListener("scroll", handleCardScroll)
    }
  })
})

// 校验规则
function validateCreateMode() {
  if (isEmpty(selectedId.value)) {
    return Promise.reject("请选择创建模式")
  }
  return Promise.resolve()
}
async function handleCreateMode() {
  tagsViewStore.delVisitedView(route)
  // 验证当前步骤
  const isValid = await validateCreateMode()
  if (selectedId.value !== "no-select") {
    createImportTask(selectedId.value as string).then(async ({ data }: any) => {
      const taskDataRes = await getTaskInfoApi(data.task_id)
      const taskData = taskDataRes.data as ViewInfo
      if (isEmpty(taskData.data_collections)) {
        taskData.data_collections = INIT_DATE_COLLECTION
      }
      taskData.task_id = data.task_id

      router.replace({ name: "MyProjectDeductCreate", query: {
        id: taskData.task_id
      } })
    })
  } else {
    router.replace({ name: "MyProjectDeductCreate" })
  }
}
function handleCancel() {
  // 先跳转到列表页
  router.replace({ name: "MyProjectDeductIndex" })
}
// 暴露验证方法给父组件
// defineExpose({
//   validate: async () => {
//     try {
//       await validateCreateMode()
//       return true
//     } catch (error: any) {
//       ElMessage.error(error)
//       return false
//     }
//   }
// })
</script>

<template>
  <div class="mode-wrapper"  style="padding: 20px 20px" ref="cardScrollContainer" v-infinite-scroll="cardLoadData"
    :infinite-scroll-disabled="infiniteScrollConfig.disabled" :infinite-scroll-distance="infiniteScrollConfig.distance"
    :infinite-scroll-immediate="infiniteScrollConfig.immediate">
    <div class="cpi-header">
      <span class="cpi-header-text">新建空白任务</span>
    </div>
    <div class="create-content">
      <div class="custom-card-container">
        <ScenarioCard :selected="selectedId == 'no-select'" :data="{ task_id: 'no-select' }"
          @toggle-select="handleToggleSelect" />
      </div>
    </div>
    <div class="cpi-header">
      <span class="cpi-header-text">从训练任务导入</span>
      <div class="cc-search-common">
        <el-input v-model="searchKey" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="handleSearch">
          <template #append>
            <el-button :icon="Search" v-throttle="() => handleSearch()" />
          </template>
        </el-input>
      </div>
    </div>
    <div class="import-content">
      <div class="custom-card-container">
        <template v-for="(item, index) in tableData" :key="index">
          <ScenarioCard :selected="selectedId != undefined && item.task_id == selectedId" :data="item"
            @toggle-select="handleToggleSelect" />
        </template>
      </div>
    </div>
    <div class="mode-loading-indicator">
      <div v-if="isLoading" class="loading-more">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
        <span>加载中...</span>
      </div>
      <div v-else-if="hasMoreData" class="loading-more">
        <i class="fas fa-angle-double-down el-icon" />
        <span>下拉加载更多数据...</span>
      </div>
      <div v-else-if="!hasMoreData && tableData.length > 0" class="no-more-data">
        <span>没有更多数据了</span>
      </div>
      <div v-else-if="tableData.length === 0" class="no-data">
        <span>暂无数据</span>
      </div>
    </div>
    <div class="mode-actions">
      <el-button @click="handleCancel">
        取消
      </el-button>
      <el-button type="primary" v-throttle="() => handleCreateMode()">
        创建
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.mode-loading-indicator {
  height: 50px;
  padding: 20px 0;
  text-align: center;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;

  .loading-more,
  .no-more-data,
  .no-data {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 14px;

    .el-icon {
      margin-right: 8px;
    }
  }

  .no-more-data,
  .no-data {
    color: #c0c4cc;
  }
}

.mode-wrapper {
  overflow: auto;
  padding-right: 10px;
  @extend %scrollbar;
}
.mode-actions {
  position: fixed;
  width: 100%;
  height: 60px;
  bottom: -30px;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000B15;
}
.create-content:not(:last-child) {
  margin-bottom: var(--main-padding);
}

.custom-card-container {
  $border-color: #223448;
  height: 100%;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  grid-auto-rows: 240px; // 设置行高以保持宽高比为3:4
  gap: 20px;
  padding: 5px 0 0px 10px !important;
  overflow: hidden;
}

.custom-card-container>* {
  min-width: 0;
}
</style>
